import { createApp, h, ref } from 'vue'
import Popup from '@c/Popup.vue'
import m from '@s/m'
// import loading from '@d/loading'

let inst
window.eTranslator = (input, lang)=>{
    console.log(input)
    console.log(input.value)
    if(input && input instanceof HTMLInputElement || input instanceof  HTMLTextAreaElement){
        let rect = input.getBoundingClientRect()

        let mainDIV = document.createElement('div')
        document.querySelector('body').appendChild(mainDIV)
        let visible = ref(true)
        let content = ref(input.value)
        let contentAfterTranslate = ref('')
        let app = createApp({
            render(){
                return h(Popup, {
                    content: content.value,
                    lang,
                    top: rect.bottom,
                    left: rect.left,
                    // v-model:visible
                    visible: visible.value,
                    'onUpdate:visible': val=>{
                        visible.value = val
                    },
                    'onUpdate:contentAfterTranslate': val=>{
                        contentAfterTranslate.value = val
                    }
                })
            }
        }, )
        // app.use(loading)
        app.mount(mainDIV)
        return {
            visible,
            content,
            contentAfterTranslate,

            app,
            hide(){
                visible.value = false
            },
            toggle(){
                visible.value = !visible.value
            },
            show(){
                visible.value = true
            },
            destroy(){
                visible.value = false
                setTimeout(()=>{
                    app.unmount()
                    mainDIV.remove()
                }, 1000)
            }
        }
    }
}

const symbolIsInputBinded = Symbol('__isInputBinded')

function getLangs(){
    return m.background('getLangs')
}
function getLang(langs, i){
    return langs[i % langs.length]
}

function isTextSelected(input) {
    if (typeof input.selectionStart == "number") {
        return input.selectionStart === 0 && input.selectionEnd === input.value.length;
    } else if (typeof document.selection != "undefined") {
        input.focus();
        return document.selection.createRange().text === input.value;
    }
}


function initInput(input){
    if(input instanceof HTMLInputElement){
        if(!input[symbolIsInputBinded]){
            input[symbolIsInputBinded] = true
            // init
            input.langIndex = 0
            // bind input
            input.addEventListener('blur', ()=>{
                inst?.destroy()
                inst = null
            })
            input.addEventListener('input', ()=>{
                inst?.destroy()
                inst = null
            })
            input.addEventListener('keydown', e=>{
                let isNeedPopup
                if (isTextSelected(input)) {
                    isNeedPopup = (e.metaKey || e.ctrlKey ) && e.key === 'a'
                }
                let isNeedTranslate = ((e.metaKey || e.ctrlKey ) && e.key === 'Enter' ) && !!inst
                let isNeedChangeLang = !!inst && e.key === 'Tab'
                if(isNeedPopup || isNeedTranslate || isNeedChangeLang){
                    m.background('isLogin').then(isLogin=>{
                        if(isLogin){
                            if(isNeedPopup){
                                // get langs
                                getLangs().then(langs=>{
                                    console.log(input)
                                    let lang = getLang(langs, input.langIndex)
                                    inst?.destroy()
                                    if(e.target.value){
                                        inst = eTranslator(e.target, lang)
                                    }
                                })
                            }
                            if(isNeedTranslate){
                                let val = inst.contentAfterTranslate?.value
                                if(val){
                                    input.value = val
                                    inst.destroy()
                                }
                            }
                            if(isNeedChangeLang){
                                getLangs().then(langs=>{
                                    let lang = getLang(langs, ++input.langIndex)
                                    inst?.destroy()
                                    if(e.target.value){
                                        inst = eTranslator(e.target, lang)
                                    }
                                })
                            }
                        }
                    })
                    e.preventDefault()
                }
            })
        }
    }
}

function initTextarea(textarea){
    console.log(textarea)
    console.log(textarea instanceof HTMLTextAreaElement)
    if(textarea instanceof HTMLTextAreaElement){
        console.log(textarea[symbolIsInputBinded])
        if(!textarea[symbolIsInputBinded]){
            textarea[symbolIsInputBinded] = true
            // init
            textarea.langIndex = 0
            // bind input
            textarea.addEventListener('blur', ()=>{
                inst?.destroy()
                inst = null
            })
            textarea.addEventListener('textarea', ()=>{
                inst?.destroy()
                inst = null
            })
            textarea.addEventListener('keydown', e=>{
                let isNeedPopup
                if (isTextSelected(textarea)) {
                    isNeedPopup = (e.metaKey || e.ctrlKey ) && e.key === 'a'
                }
                let isNeedTranslate = ((e.metaKey || e.ctrlKey ) && e.key === 'Enter' ) && !!inst
                let isNeedChangeLang = !!inst && e.key === 'Tab'
                if(isNeedPopup || isNeedTranslate || isNeedChangeLang){
                    m.background('isLogin').then(isLogin=>{
                        if(isLogin){
                            if(isNeedPopup){
                                // get langs
                                getLangs().then(langs=>{
                                    let lang = getLang(langs, textarea.langIndex)
                                    inst?.destroy()
                                    if(e.target.value){
                                        inst = eTranslator(e.target, lang)
                                    }
                                })
                            }
                            if(isNeedTranslate){
                                let val = inst.contentAfterTranslate?.value
                                if(val){
                                    textarea.value = val
                                    inst.destroy()
                                }
                            }
                            if(isNeedChangeLang){
                                getLangs().then(langs=>{
                                    let lang = getLang(langs, ++textarea.langIndex)
                                    inst?.destroy()
                                    if(e.target.value){
                                        inst = eTranslator(e.target, lang)
                                    }
                                })
                            }
                        }
                    })
                    e.preventDefault()
                }
            })
        }
    }
}

document.addEventListener('click', e=>{
    if (e.target instanceof HTMLTextAreaElement) {
        initTextarea(e.target)
    } else {
        initInput(e.target)
    }
}, {capture: true})
document.addEventListener('input', e=>{
    console.log(e)
    initInput(e.target)
})

document.addEventListener('textarea', e=>{
    console.log(e)
    initTextarea(e.target)
})
